var gulp = require('gulp');

var cleanCss = require('gulp-clean-css');  // 压缩CSS
var uglify = require('gulp-uglify');  // 压缩JS
var htmlmin = require('gulp-htmlmin');  // 压缩HTML
var clean = require('gulp-clean');  // 删除文件
var rev = require('gulp-rev');  // 文件加md5
var revReplace = require('gulp-rev-replace');  // 替换路径
var revFormat = require('gulp-rev-format');  // 替换格式化
var replace = require('gulp-replace');  // 替换内容
var foal = require('gulp-foal')();  // 带参数的任务
var sequence = require('gulp-sequence');  // 按顺序执行任务，gulp默认是异步
var fs = require('fs');  // 获取当前脚本的绝对路径

// 输出路径
var buildPath = 'build/';

// 压缩css
foal.task('cssMinOne', (src, dest) => {
    return gulp.src(src).pipe(cleanCss()).pipe(gulp.dest(dest));
});
gulp.task('cssMinAll', (callback) => {
    foal.run(foal.cssMinOne(buildPath+'css/**/*.css', buildPath+'css/'), callback);
});

// 压缩js
foal.task('jsMinOne', (src, dest) => {
    return gulp.src(src).pipe(uglify()).pipe(gulp.dest(dest));
});
gulp.task('jsMinAll', (callback) => {
    foal.run(foal.jsMinOne(buildPath+'js/**/*.js', buildPath+'js/'), callback);
});

// 压缩html
foal.task('htmlMinOne', (src, dest) => {
    var options = {
        removeComments: true,  // 清除HTML注释
        collapseWhitespace: true,  // 压缩HTML
        minifyJS: true,  // 压缩页面JS
        minifyCSS: true,  // 压缩页面CSS
    }
    return gulp.src(src).pipe(htmlmin(options)).pipe(gulp.dest(dest));
});
gulp.task('ihMin', (callback) => {
    foal.run(foal.htmlMinOne(buildPath+'ih/**/*.html', buildPath+'ih/'), callback);
});
gulp.task('indexMin', (callback) => {
    foal.run(foal.htmlMinOne(buildPath+'*.html', buildPath), callback);
});
gulp.task('htmlMinAll', (callback) => {
    return sequence('ihMin', 'indexMin')(callback);
});

// 复制
gulp.task('copy', (callback) => {
    gulp.task('ihCopy', (callback) => {
        return gulp.src('ih/**/*').pipe(gulp.dest(buildPath+'ih/'));
    });
    gulp.task('cssCopy', (callback) => {
        return gulp.src(['css/**/*']).pipe(gulp.dest(buildPath+'css/'));
    });
    gulp.task('jsCopy', (callback) => {
        return gulp.src('js/**/*').pipe(gulp.dest(buildPath+'js/'));
    });
    gulp.task('imgCopy', (callback) => {
        return gulp.src('img/**/*').pipe(gulp.dest(buildPath+'img/'));
    });
    gulp.task('indexCopy', (callback) => {
        return gulp.src('*.html').pipe(gulp.dest(buildPath));
    });
    gulp.task('pluginsCopy', (callback) => {
        return gulp.src('plugins/**/*').pipe(gulp.dest(buildPath+'plugins/'));
    });
    return sequence('ihCopy', 'cssCopy', 'jsCopy', 'indexCopy', 'imgCopy', 'pluginsCopy')(callback);
});

// 清除
gulp.task('clean', (callback) => {
    return gulp.src([buildPath, 'rev/']).pipe(clean());
});

// 生成文件与版本号的对应文件rev-manifest.json
gulp.task('addMd5', (callback) => {  
    return gulp.src(['css/**/*', 'js/**/*', 'ih/**/*', 'img/**/*'])  
                .pipe(rev())
                .pipe(revFormat({  
                    prefix: '.',  
                    suffix: '.v',  // .v用于正则表达式匹配
                    lastExt: false  
                }))
                .pipe(rev.manifest())  
                .pipe(gulp.dest('rev/'));  
});  

// 更新版本号
foal.task('revOne', (src, dest) => {  
    var manifest = gulp.src('rev/rev-manifest.json');  
    function modifyUnreved(filename) {
        return filename;  
    }  
    function modifyReved(filename) { 
        if (filename.indexOf('.v') > -1) {  
            const _version = filename.match(/\.[\w]*\.v/)[0].replace(/(\.|v)*/g, '');  
            const _filename = filename.replace(/\.[\w]*\.v/, '');  
            filename = _filename + '?v=' + _version;  
            return filename;  
        }  
        return filename;  
    }
    return gulp.src(src)
                // 删除原来的版本号，文件扩展名匹配css、js、html、png、gif，版本号末尾匹配'、"、&、)、-
                // main.html中的timeline-api.js?bundle=不需要增加版本号
                .pipe(replace(/(\.(?:css|js|html|png|gif))\?(?!bundle=)(v=)?[^\'\"\&\)\-]*/g, '$1'))  
                .pipe(revReplace({
                    manifest: manifest,  
                    modifyUnreved: modifyUnreved,  
                    modifyReved: modifyReved  
                }))    
                .pipe(gulp.dest(dest));
});
gulp.task('ihRev', (callback) => {
    return foal.run(foal.revOne(buildPath+'ih/**/*', buildPath+'ih/'), callback);
});
gulp.task('cssRev', (callback) => {
    return foal.run(foal.revOne(buildPath+'css/**/*', buildPath+'css/'), callback);
});
gulp.task('jsRev', (callback) => {
    return foal.run(foal.revOne(buildPath+'js/**/*', buildPath+'js/'), callback);
});
gulp.task('indexRev', (callback) => {
    return foal.run(foal.revOne(buildPath+'*.html', buildPath), callback);
});
gulp.task('revAll', (callback) => {
    return sequence('ihRev', 'cssRev', 'jsRev', 'indexRev')(callback);
}); 

// 替换版本号前对文件的特殊引用进行处理
foal.task('extra', (src, dest) => {
    gulp.src(src)
        // js/settings/中templateUrl -- 修改路径、增加版本号
        .pipe(replace(/(templateUrl: ['"])([^\'\"]*)/g, '$1/../ih/settings/$2'))
        // monitor.html中带参数跳转到main.html -- 修改路径、增加版本号
        .pipe(replace(/(window.open\(['"])(main.html\?)([^\'\"]*)/g, '$1/../ih/console/$2v=&$3')) 
        .pipe(gulp.dest(dest));
});
gulp.task('extra1', (callback) => {
    foal.run(foal.extra('js/settings/*.js', buildPath+'js/settings/'), callback);
});
gulp.task('extra2', (callback) => {
    foal.run(foal.extra('ih/console/*.html', buildPath+'ih/console/'), callback);
});
gulp.task('extraInit', (callback) => {
    return sequence('extra1', 'extra2')(callback);
});

// 初始化
gulp.task('default', (callback) => {
    return sequence('clean', 'copy', 'addMd5', 'extraInit', 'revAll',
                    'htmlMinAll', 'cssMinAll', 'jsMinAll')(callback);
});